Asg = function(){};
Asg.constants = function(){};
Asg.constants.APPLICATION_TITLE = "RED NACIONAL DE EMPLEO";
Asg.constants.CONTEXT_PATH = "renacempleo";
Asg.constants.GT_ZERO_TEXT = "El valor de este campo debe ser mayor que cero";
Asg.constants.EQGT_ZERO_TEXT = "El valor de este campo debe ser igual o mayor que cero";
Asg.constants.GT_ZERO_VALUE_WITH_DECIMAL = 0.01;
Asg.constants.EQGT_ZERO_VALUE_WITH_DECIMAL = 0.00;
Asg.constants.GT_ZERO_VALUE_WITHOUT_DECIMAL = 1;
Asg.constants.EQGT_ZERO_VALUE_WITHOUT_DECIMAL = 0;
Asg.constants.INVALID_ACTION = "Acci\u00F3n inv\u00E1lida.";
Asg.constants.REQUIRED_FIELDS = "Campos requeridos o con valor inv\u00E1lido";
Asg.constants.CONNECTION_FAIILURE = "Problemas al intentar conectarse con el servidor";
Asg.constants.SESSION_EXPIRED = "* Su sesi\u00F3n ha caducado, debe  ingresar nuevamente";
Asg.constants.ERROR_404 = "* Recurso no Disponible";
Asg.constants.DEFAULT_ERROR_MESSAGE = "Procesamiento Incorrecto";
Asg.constants.CONFIRM_DELETE_MESSAGE = "\u00BFEst\u00E1 seguro que desea eliminar el registro?";
Asg.constants.CONFIRM_INACTIVATE_MESSAGE = "\u00BFEst\u00E1 seguro que desea inactivar el registro?";
Asg.constants.CONFIRM_ACTIVATE_MESSAGE = "\u00BFEst\u00E1 seguro que desea activar el registro?";
Asg.constants.VALIDATE_DOCUMENT = "Su tipo y numero de documento de validacion ya se encuentra registrado";
Asg.constants.TIMEOUT_SECONDS = 300000;
Asg.constants.PAGE_SIZE = 50;

Asg.constants.OPEN_ICON = "open_icon";
Asg.constants.ADD_ICON = "add_icon";
Asg.constants.EDIT_ICON = "edit_icon";
Asg.constants.SAVE_ICON = "save_icon";
Asg.constants.DELETE_ICON = "delete_icon";
Asg.constants.CANCEL_ICON = "cancel_icon";
Asg.constants.SEARCH_ICON = "search_icon";
Asg.constants.HOME_ICON = "home_icon";
Asg.constants.REFRESH_ICON = "refresh_icon";
Asg.constants.PDF_ICON = "pdf_icon";
Asg.constants.ACCEPT_ICON = "accept_icon";
Asg.constants.REQUIRED = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>'; 
Asg.constants.LABEL_STYLE_TEXT= "font-weight:bold;color: #585858;";



Asg.constants.CTG_TPER_NATURAL = "00023";



Asg.Utils = function(){
	return {
		getComponent: function(component){
			if(typeof component == "string") return Ext.getCmp(component);
			return component;
		},
		setVisible: function(field, visible){
			field = Asg.Utils.getComponent(field);
			if(field && field.setVisible){
				field.setVisible(visible);
			}
		},
		getValue : function(field){
			field = Asg.Utils.getComponent(field);
			if(field && field.getValue) return field.getValue();
			return "";
		},
		setValue : function(field, value){
			field = Asg.Utils.getComponent(field);
			if(field && field.setValue) return field.setValue(value);
		},
		setFocus: function(field){
			field = Asg.Utils.getComponent(field);
			if(field && field.focus) field.focus();
		},
		setEnable: function(field, enable){
			field = Asg.Utils.getComponent(field);
			if(field && field.setDisabled) field.setDisabled(!enable);
			if(field && field.clearInvalid) field.clearInvalid();
		},
		setDefaultValue: function(field, defaultValue){
			field = Asg.Utils.getComponent(field);
			if(field) field.defaultValue = defaultValue;
		},
		//AJAX
		ajaxRequestGetJson : function(result){
			try{
				return Ext.JSON.decode(result.responseText);
			}catch(e){if(console) console.log(e);}
		},
		ajaxstatusDecode: function(status, responseText, options){
			if(Ext.isEmpty(responseText)){
				Asg.Message.alertInvalid(Asg.constants.CONNECTION_FAIILURE);
				options.callback = null;
				return false;
			}
			if(responseText && !Ext.isEmpty(responseText) && responseText.indexOf("bWFyaW9yMjM=") != -1){
				Asg.Message.confirmProcess(Asg.constants.SESSION_EXPIRED, function(){
					document.location.href = Asg.constants.CONTEXT_PATH + "/security/logout";
				});
				options.callback = null;
				return false;
			}
			if(responseText.indexOf("No data received from server") != -1 ||
					(status != null && (status.toString().indexOf("404") != -1 || status.toString().indexOf("500") != -1))){
				Asg.Message.alertInvalid(Asg.constants.ERROR_404);
				options.callback = null;
				return false;
			}
			return true;
		},
		ajaxRequestComplete: function(conn, response, options){
			if(response && !Ext.isEmpty(response.responseText)) response.responseText = response.responseText.replace(/<\/?pre[\s|\w|=|"|\-|\:|;]*>/ig, "");
			Asg.Utils.ajaxstatusDecode(response.status, response.responseText, options);
		},
		formatString : function (B) { var A = Array.prototype.slice.call(arguments, 1); return B.replace(/\{(\d+)\}/g, function (C, D) {return A[D];});},
		parseDate: function(value, format, inputFormat){
			if(Ext.isEmpty(value)) return value;
			try{
				if(Ext.isDate(value))
					return Ext.Date.format(value, format || "d/m/Y");
				return Ext.Date.format(Ext.Date.parse(value, inputFormat || "Ymd"), format || "d/m/Y");
			}catch(e){if(console && console.log) console.log(e);}
			return value;
		}
	};
}();

Asg.Form = function(){
	return {
		defaults: function(config){
			if(!config) config = {};
			config.enforceMaxLength = true;
			config.maxLength = 200;
			config.typeAhead = true;
			config.minChars = 1;
			config.queryMode = "local";
			config.forceSelection = true;
			config.selectOnFocus = true;
			config.triggerAction = "all";
			config.allowEnable = true;
			return config;
		},
		setEnable: function(form, enable){
			if(typeof form == "string"){
				form = Ext.getCmp(form);
				if(!form) return;
			}
			Ext.each(form.getForm().getFields().items, function(){
				var test = /^label$|^grid$/;
				if(!test.test(this.xtype) && this.allowEnable)
					this.setDisabled(!enable);
			});
			form.getForm().clearInvalid();
		},
		setEnableAndClear: function(form, enable){
			if(typeof form == "string"){
				form = Ext.getCmp(form);
				if(!form) return;
			}
			Ext.each(form.getForm().getFields().items, function(item){
				var test = /^label$|^grid$/;
				if(!test.test(this.xtype) && this.allowEnable){
					this.setDisabled(!enable);
					if(item.setValue){
						if(this.xtype == "checkbox") item.setValue(true);
						else this.setValue(this.defaultValue || "");
					}
				}
		    });
			form.getForm().clearInvalid();
		},
		setAllowEnable : function(field, enable){
			if(typeof field == "string") field = Ext.getCmp(field);
			if(field) field.allowEnable = enable;
		},
		switchButton: function(config, option){
			switch(option){
				case "add":
				case "edit":
					Asg.Utils.setVisible(config.add, false);
					Asg.Utils.setVisible(config.edit, false);
					Asg.Utils.setVisible(config.save, true);
					Asg.Utils.setVisible(config.cancel, true);
					break;
				case "rowclick":
					Asg.Utils.setVisible(config.edit, true);
				case "save":
				case "cancel":
					Asg.Utils.setVisible(config.add, true);
					Asg.Utils.setVisible(config.save, false);
					Asg.Utils.setVisible(config.cancel, false);
					break;
				default: break;
			}
		},
		switchForm: function(form, option){
			switch(option){
				case "add":
					Asg.Form.setEnableAndClear(form, true);
					break;
				case "edit":
					Asg.Form.setEnable(form, true);
					break;
				case "rowclick":
					Asg.Form.setEnable(form, false);
					break;
				case "saved":
				case "cancel":
					Asg.Form.setEnableAndClear(form, false);
					break;
				default: break;
			}
		},
		setValues: function(form, data){
			form = Asg.Utils.getComponent(form);
			if(form && form.getForm) form.getForm().setValues(data);
		},
		setRequired : function(field, required){
			field = Asg.Utils.getComponent(field);
			if(field) field.allowBlank = !required;
		},
		failureProcedure: function(form, action){
			Ext.Msg.hide();
			if(action.failureType == Ext.form.Action.CLIENT_INVALID)
				Asg.Message.alertInvalidFields();
			else if(action.failureType == Ext.form.Action.CONNECT_FAILURE)
				Asg.Message.alertConnectionFailure();
			else if(action.failureType == Ext.form.Action.SERVER_INVALID)
				Asg.Message.alertInvalid(action.result.message);
			else
				Efx.message.alertDefaultErrorMessage();
		},
		suspendEvents: function(form, queue){
			var form = Asg.Utils.getComponent(form);
			if(form){
				Ext.each(form.items.items, 
					function(item){if(/(textfield)|(numericfield)|(numberfield)|(combo)/.test(item.xtype)) item.suspendEvents(queue);});
			}
		},
		resumeEvents: function(form){
			var form = Asg.Utils.getComponent(form);
			if(form){
				Ext.each(form.items.items, 
					function(item){if(/(textfield)|(numericfield)|(numberfield)|(combo)/.test(item.xtype)) item.resumeEvents();});
			}
		}
	};
}();

Asg.Combo = function(){
	var ctgMediosBusqueda;
	var ctgOficinas, sgdUsuarios, ctgCargoEmpleados;
	return {
		getAllCtgMediosBusqueda: function() { return ctgMediosBusqueda;},
		initCtgMediosBusqueda: function(medio) { ctgMediosBusqueda= medio;},
		getAllCtgOficinas: function() { return ctgOficinas;},
		intiCtgOficinas: function(oficina){ ctgOficinas = oficina;},
		getAllSgdUsuarios: function() { return sgdUsuarios;},
		initSgdUsuarios: function (usuario) { sgdUsuarios = usuario;},
		getAllCtgCargoEmpleados: function() {return ctgCargoEmpleados;},
		initCtgCargoEmpleados: function(cargo){ ctgCargoEmpleados = cargo;},
		yesnoArray: function(){
			return [["1", "SI"], ["0", "NO"]];
		},
		daysOfWeek: function(){
			return [["1", "LUNES"], ["2", "MARTES"], ["3", "MIERCOLES"], ["4", "JUEVES"], ["5", "VIERNES"], ["6", "SABADO"], ["7", "DOMINGO"]];
		},
		activeInactiveArray: function(){
			return [["1", "ACTIVO"], ["0", "INACTIVO"]];
		},
		zonaResidenciaArray: function(){
			return [["1", "URBANA"], ["2", "RURAL"]];
		},
		tipoPersoneriaArray: function(){
			return [["1", "JURIDICA"], ["2", "NATURAL"]];
		},
		monthOfYear: function(){
			return [
		        ["1","ENERO"],
		        ["2","FEBRERO"],
		        ["3","MARZO"],
		        ["4","ABRIL"],
		        ["5","MAYO"],
		        ["6","JUNIO"],
		        ["7","JULIO"],
		        ["8","AGOSTO"],
		        ["9","SEPTIEMBRE"],
		        ["10","OCTUBRE"],
		        ["11","NOVIEMBRE"],
		        ["12","DICIEMBRE"]
	        ];
		},
		yearsAgo: function(){
			var currentTime = new Date();
		    var now = currentTime.getFullYear();
		    var years = [];
		    var y = (now - 40);
		    while(y<=now){
		        years.push([y]);
		        y++;
		    }
		    return years;
		},
		decodeDay: function(value){
			if(Ext.isEmpty(value)) return "";
			try{
				return Asg.Combo.daysOfWeek()[value - 1][1];
			}catch(e){}
		},
		filter: function(objectId, array, index){
			arrayToReturn = new Array();
			if(Ext.isEmpty(index)) return arrayToReturn;
			Ext.each(array, function(item){
				if(item[index] == objectId){
					hasBegan = true;
					arrayToReturn.push(item);
				}else return item[index] <= objectId;
			});
			return arrayToReturn;
		},
		filterByParameters: function(objectIds, array, indexes){
			arrayToReturn = new Array();
			if(Ext.isEmpty(indexes)) return arrayToReturn;
			Ext.each(array, function(item){
				if(item[indexes[0]] == objectIds[0] && item[indexes[1]] == objectIds[1]){
					arrayToReturn.push(item);
				}
			});
			return arrayToReturn;
		},
		removeAll: function(field, notClear){
			if(typeof field == "string") field = Ext.getCmp(field);
			if(field && field.store){
				field.store.removeAll(true);
				if(!notClear) field.setValue("");
			}
		},
		loadData: function(field, data, notClear){
			if(typeof field == "string") field = Ext.getCmp(field);
			if(field && field.store){
				this.removeAll(field, notClear);
				field.store.loadData(data);
			}
		},
		getSelectedRecord: function(combo, field, id){
			if(typeof combo == 'string') combo = Ext.getCmp(combo);
			var valueToReturn = null;
			if(combo && combo.store){
				Ext.each(combo.store.getRange(), function(item){
					if(item.get(field) == id){
						valueToReturn = item;
						return false;
					}
				});
			}
			return valueToReturn;
		}
	};
}();

Asg.Window = function(){
	return{
		openSelfWindow: function(url, parameters){
			if(Ext.get("postMethodSubmit")) Ext.get("postMethodSubmit").remove();
			var form = Ext.get(Ext.getBody()).createChild({tag: "form", method: "post", id: "postMethodSubmit"});
			if(url.indexOf("?") != -1){
				var extraParameters = url.split("?")[1];
				url = url.split("?")[0];
				if(!extraParameters.toString().isEmpty()){
					var extraParametersArray = extraParameters.split("&");
					Ext.each(extraParametersArray, function(item){
						form.createChild({tag: "input", type: "hidden", name: item.split("=")[0], value: item.split("=")[1]});
					});
				}
			}
			if(parameters){
				Ext.each(parameters, function(object, index){
					Ext.iterate(object, function(name, value) {form.createChild({tag: "input", type: "hidden", name: name, value: value});});
				});
			}
			form.dom.setAttribute("action", Asg.constants.CONTEXT_PATH + "/" + url);
			form.dom.setAttribute("target", "");
			form.dom.submit();
		},
		openWindow: function(url, parameters){
			window.open("about:blank", "window_form", 
				"location=0,scrollbars,toolbar=0,titlebar=no,status=no,resizable=no,width=850,height=700,location=no");
			if(Ext.get("postMethodSubmit")) Ext.get("postMethodSubmit").remove();
			var form = Ext.get(Ext.getBody()).createChild({tag: "form", method: "post", id: "postMethodSubmit"});
			if(url.indexOf("?") != -1){
				var extraParameters = url.split("?")[1];
				url = url.split("?")[0];
				if(!extraParameters.toString().isEmpty()){
					var extraParametersArray = extraParameters.split("&");
					Ext.each(extraParametersArray, function(item){
						form.createChild({tag: "input", type: "hidden", name: item.split("=")[0], value: item.split("=")[1]});
					});
				}
			}
			if(parameters){
				Ext.each(parameters, function(object, index){
					Ext.iterate(object, function(name, value) {form.createChild({tag: "input", type: "hidden", name: name, value: value});});
				});
			}
			form.dom.setAttribute("action", Asg.constants.CONTEXT_PATH + "/" + url);
			form.dom.setAttribute("target", "window_form");
			form.dom.submit();
		}
	};
}();

Asg.Message = function(){
	return {
		alert: function(message){
			Ext.MessageBox.show({
				title: Asg.constants.APPLICATION_TITLE,
				toFrontOnShow: true,
				msg: message,
				buttons: Ext.Msg.OK,
				minWidth: 250
			});
			Ext.MessageBox.toFront();
		},
		alertInvalidFields: function(message){
			this.alert(Asg.Utils.formatString("<b>{0}</b><br />* {1}<br />{2}", Asg.constants.INVALID_ACTION, Asg.constants.REQUIRED_FIELDS, (message || "")));
		},
		alertConnectionFailure: function(){
			this.alert(Asg.constants.CONNECTION_FAIILURE);
		},
		alertInvalid: function(message){
			this.alert(Asg.Utils.formatString("<b>{0}</b><br /> {1}", Asg.constants.INVALID_ACTION, message));
		},
		alertDefaultErrorMessage: function(){
			this.alert(Asg.constants.DEFAULT_ERROR_MESSAGE);
		},
		confirmDelete: function(fn, parameters){
			if(!parameters) parameters = {};
			Ext.MessageBox.show({
				title: Asg.constants.APPLICATION_TITLE,
				msg: Asg.constants.CONFIRM_DELETE_MESSAGE,
				fn: function(btn){
					if(btn == "ok") fn(parameters);
				},
				buttons: Ext.Msg.OKCANCEL,
				minWidth: 250
			});
			Ext.MessageBox.toFront();
		},
		confirmProcess: function(message, fn, parameters){
			Ext.MessageBox.show({
				title: Asg.constants.APPLICATION_TITLE,
				msg: message,
				fn: function(){
					fn(parameters);
				},
				buttons: Ext.Msg.OK,
				closable: false,
				minWidth: 250
			});
			Ext.MessageBox.toFront();
		},
		confirm: function(message, fn){
			Ext.MessageBox.show({
				title: Asg.constants.APPLICATION_TITLE,
				msg: message,
				fn: fn,
				buttons: Ext.Msg.YESNO,
				minWidth: 250,
				closable: false
			});
			Ext.MessageBox.toFront();
		},
		errorDelete: function(message, fn){
			Ext.MessageBox.show({
				title: "ERROR",
				msg: message,
				fn: fn,
				icon: Ext.MessageBox.ERROR,
				buttons: Ext.Msg.OK,
				minWidth: 250,
				closable: false
			});
			Ext.MessageBox.toFront();
		},
		progress: function(message){
			Ext.MessageBox.show({
				title: Asg.constants.APPLICATION_TITLE,
				msg: message,
				buttons: [],
				minWidth: 250,
				height: 70,
				closable: false
			});
			Ext.MessageBox.toFront();
		},
		prompt: function(message, fn, onEsc){
			Ext.MessageBox.show({
				title: Asg.constants.APPLICATION_TITLE,
				msg: message,
				buttons: Ext.Msg.OKCANCEL,
				minWidth: 350,
				height: 70,
				fn: fn,
				prompt: true,
				closable: false
			});
			Ext.MessageBox.toFront();
		}
	};
}();

Ext.apply(Ext.form.VTypes, {
	telefonoDomicilioVal: /^([2|6|7][0-9]{3})-([0-9]{4})$/,
	telefonoDomicilioMask: /[\d\-]/i,
	telefonoDomicilioText: "N\u00FAmero de Telefonico Fijo inv\u00E1lido, debe comenzar con 2, 6 o 7 y ser de 8 digitos con guion",
	telefonoDomicilio: function(v){
		return this.telefonoDomicilioVal.test(v);
	}
});

Ext.apply(Ext.form.VTypes, {
	telefonoCelularVal:  /^([6|7][0-9]{3})-([0-9]{4})$/,
	telefonoCelularMask: /[\d\-]/i,
	telefonoCelularText: "N\u00FAmero de Telefonico Fijo inv\u00E1lido, debe comenzar con 6 o 7 y ser de 8 digitos con guion",
	telefonoCelular: function(v){
		return this.telefonoCelularVal.test(v);
	}
});

Ext.apply(Ext.form.VTypes, {
	telefonoVal: /^([2|6|7][0-9]{3})-([0-9]{4})$/,
	telefonoMask: /[\d\-]/i,
	telefonoText: "N\u00FAmero de Telefonico Fijo inv\u00E1lido, debe comenzar con 2, 6 o 7 y ser de 8 digitos con guion",
	telefono: function(v){
		return this.telefonoVal.test(v);
	}
});

Ext.apply(Ext.form.VTypes, {
	duiVal: /^\d{9}$/,
	duiMask: /^\d{0,9}$/,
	duiText: 'Formato DUI inv\u00E1lido',
	dui: function(value){
		if(isNaN(parseFloat(value)) || parseFloat(value) == 0) return false;
		var cuerpo = value.substring(0, 8);
		var digitoVerif = value.substring(8, 9);
		if(Ext.isEmpty(cuerpo) || Ext.isEmpty(digitoVerif) || value.length != 9) return false;
		var i, k = 0, suma = 0, sumando, digito, resto, digito1;
		digito = Number(digitoVerif);
		for(i = 9; i > 1; i--){
			sumando = cuerpo.substr(k, 1);
			suma += Number(sumando) * i;
			k++;
		}
		resto = suma % 10;//30
		if(resto == 0) digito1 = 0;
		else digito1 = 10 - resto;
		if(digito != digito1) return false;
		return true;
	}
});

Ext.apply(Ext.form.VTypes, {
	nitVal: /^\d{13}$/,
	nitMask: /^\d{0,13}$/,
	nitText: 'Formato NIT inv\u00E1lido',
	nit: function(value){
		if(isNaN(parseFloat(value)) || parseFloat(value) == 0) return false;
		var frontera, peso,suma=0, digito,i, aux, aux1,factor, dig_verif;
		if(Ext.isEmpty(value) || value.length != 14)
			return false;
		frontera = Number(value.substring(10,13));
		if(frontera < 100){
			for(i = 0; i < 13; i++){
				peso = Number(value.substring(i, i+1)) * (15 - (i+1));
				suma += peso;
			}
			digito=suma % 11;
			if(digito == 10) digito=0;
		}
		else{
			for(i = 0; i < 13; i++){
				aux = ((i+1) + 4) / 6;
				aux1 = Math.floor(aux);
				factor = (3 + (6 * aux1)) - (i+1);
				peso = Number(value.substring(i, i+1)) *factor;
				suma += peso;
			}
			digito = suma%11;
			if(digito > 1) digito = 11 - digito;
			else digito = 0;
		}
		dig_verif = Number(value.substr(13, 1));
		if(digito != dig_verif)	return false;
		return true;
	}
});

Ext.apply(Ext.form.VTypes, {
	horaVal: /^(0[1-9]|1[0-2]):(0[0-9]|[1-5][0-9])$/,
	horaMask: /\d|\:/,
	horaText: 'Formato ##:## Ej. 12:30',
	hora: function(v){
		return this.horaVal.test(v);
	}
});

//25-09-2012, Hugo Gonzalez, EDC
//********************************************************************************/

Ext.apply(Ext.form.VTypes, {
	letraVal: /^[A-Za-z+][\s[A-Za-z]+]*$/,
	letraMask: /[a-z ]/i,
	letraText: 'Este campo permite solamente letras',
	letra: function(v){
		return this.letraVal.test(v);
	}
});
Ext.apply(Ext.form.VTypes, {
	letraparentesisVal: /^[A-Za-z+][\s[A-Za-z-\)]+]*$/,
	letraparentesisMask: /[a-z ]/i,
	letraparentesisText: 'Este campo permite solamente letras',
	letraparentesis: function(v){
		return this.letraparentesisVal.test(v);
	}
});
Ext.apply(Ext.form.VTypes, {
	letranumVal: /^[a-zA-Z0-9]+$/,
	letranumMask: /[a-z0-9 ]/i,
	letranumText: 'Este campo permite solamente letras y numeros',
	letranum: function(v){
		return this.letranumVal.test(v);
	}
});
Ext.apply(Ext.form.VTypes, {
	nrcVal: /^[0-9]+$/,
	nrcMask: /[\d\/]/,
	nrcText: "N\u00FAmero de Registro inv\u00E1lido",
	nrc: function(v){
		return this.nrcVal.test(v);
	}
});

Ext.apply(Ext.form.VTypes, {	
	docDemandante: function(value, field){		
		 var comp = Ext.getCmp('ctgDocumento.ctgDocumentoId');
         if(comp.getValue()==3){//Si es igual a DUI
      	   //Agregar a campo de texto validacion de tipo Dui
        	if(isNaN(parseFloat(value)) || parseFloat(value) == 0) return false;
     		var cuerpo = value.substring(0, 8);
     		var digitoVerif = value.substring(8, 9);
     		if(Ext.isEmpty(cuerpo) || Ext.isEmpty(digitoVerif) || value.length != 9) return false;
     		var i, k = 0, suma = 0, sumando, digito, resto, digito1;
     		digito = Number(digitoVerif);
     		for(i = 9; i > 1; i--){
     			sumando = cuerpo.substr(k, 1);
     			suma += Number(sumando) * i;
     			k++;
     		}
     		resto = suma % 10;//30
     		if(resto == 0) digito1 = 0;
     		else digito1 = 10 - resto;
     		if(digito != digito1) return false;
     		return true;      	         	  
         }
		return true;
	},
	docDemandanteText: "N\u00FAmero de Documento inv\u00E1lido",
});
// End EDC
//********************************************************************************/

Asg.Grid = function(){
	return {
		clearSelection: function(grid){
			grid = Asg.Utils.getComponent(grid);
			if(!grid || !grid.rendered) return;
			grid.getSelectionModel().deselectAll();
		},
		loadData: function(grid, data){
			grid = Asg.Utils.getComponent(grid);
			if(grid && grid.getStore){
				grid.getStore().removeAll(true);
				grid.getStore().loadData(data);
			}
		},
		hasSelection: function(grid){
			grid = Asg.Utils.getComponent(grid);
			if(!grid || !grid.rendered || !grid.getSelectionModel) return false;
			return grid.getSelectionModel().hasSelection();
		},
		getSelectedRow : function(grid){
        	if(typeof grid == "string") grid = Asg.Utils.getComponent(grid);
        	if(!grid) return null;
			var records = grid.getSelectionModel().getSelection();
			if(records != null && records.length > 0) return records[0];
			return null;
		},
		updateSelectedRow: function(grid, field, value){
			var record = Asg.Grid.getSelectedRow(grid);
			if(record) record.set(field, value);
		},
		getAdditionalData: function(data, idx, record, orig) {
            var o = Ext.grid.feature.RowBody.prototype.getAdditionalData.apply(this, arguments),
                id = this.columnId;
            o.rowBody = this.getRowBodyContents(data);
            o[id + '-tdAttr'] = ' valign="top" rowspan="2" ';
            if (orig[id+'-tdAttr']) {
                o[id+'-tdAttr'] += orig[id+'-tdAttr'];
            }
            return o;
        }
	};
}();


Asg.Acciones = function(){
	return{
		buscarEmpresas: function(){
			var store = Ext.getCmp("gridEmpresas").getStore();
			store.currentPage = 1;
			store.load();
		},
		guardarEmpresa: function(){
			var form = Ext.getCmp("formDatosEmpresa").getForm();
			if(!form.isValid()){
				Asg.Message.alertInvalidFields();
				return;
			}
			form.standardSubmit = true;
			Asg.Message.progress("Guardando Cliente...");
			form.submit({
			    url: Asg.constants.CONTEXT_PATH + "/red/empresas/guardarEmpresa",
			    params: {
			    	"redEmpresas.redEmpresaNit": Asg.Utils.getValue("redEmpresaNit"),
			    	"redEmpresas.redEmpresaRegistro": Asg.Utils.getValue("redEmpresaRegistro"),
			    	"redEmpresas.sgdUsuario.sgdUsuarioId": Asg.Utils.getValue("sgdUsuario"),
			    	"redEmpresas.ctgOficina.ctgOficinaId": Asg.Utils.getValue("ctgOficina")
			    }
			});
		},
		validarEmpresa: function(){
			var form = Ext.getCmp("formRegistroEmpresas").getForm();
			if(!form.isValid()){
				Asg.Message.alertInvalidFields();
				return;
			}
			Ext.Ajax.request({
				timeout: Asg.constants.TIMEOUT_SECONDS,
			    url: Asg.constants.CONTEXT_PATH + "/red/empresas/validarEmpresa",
			    params: {
			    	redEmpresaNit: Asg.Utils.getValue("redEmpresaNit"),
					redEmpresaRegistro: Asg.Utils.getValue("redEmpresaRegistro")
			    },
			    callback: function(options, success, response){
			    	if(success){
			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
			    		if(jsonObject){
			    			if(jsonObject.validate)
			    				Asg.Message.alert("Empresa ya existe en RENACEMPLEO");
			    			else 
			    				RedEmpresa.next();
			    		}
			    	}
			    }
			});
		}
	};
}();

Ext.Ajax.clearListeners();
Ext.Ajax.on("requestcomplete", Asg.Utils.ajaxRequestComplete);
Ext.Ajax.on("requestexception", Asg.Utils.ajaxRequestComplete);

//http://www.htmlgoodies.com/html5/javascript/calculating-the-difference-between-two-dates-in-javascript.html#fbid=0WJmK7YZv5A
Date.yearsBetween = function( date1, date2 ) {
	  //Get 1 day in milliseconds
	  var one_year=(1000*60*60*24) * 365;
	  // Convert both dates to milliseconds
	  var date1_ms = date1.getTime();
	  var date2_ms = date2.getTime();
	  // Calculate the difference in milliseconds
	  var difference_ms = date2_ms - date1_ms;	    
	  // Convert back to days and return
	  return Math.round(difference_ms/one_year);
}
